package com.laikan.reader.bookreader.engines;

import android.app.Activity;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;
import com.laikan.library.httpvolley.engine.HttpApiRequestEngine;
import com.laikan.library.httpvolley.engine.Requester;
import com.laikan.library.httpvolley.helper.RequestListener;
import com.laikan.library.httpvolley.helper.VolleyErrorHandler;
import com.laikan.library.httpvolley.response.HttpResponse;
import com.laikan.library.managers.ToastMgr;
import com.laikan.library.utils.SPUtil;
import com.laikan.reader.bookreader.activity.ReaderDetailActivity;
import com.laikan.reader.comment.APIProtocol;
import com.laikan.reader.comment.Constants;
import com.laikan.reader.core.bean.BaseDataBean;
import com.laikan.reader.core.bean.ChapterBean;
import com.laikan.reader.core.bean.ChapterDetailBean;
import com.laikan.reader.core.utils.ActivityUitl;
import com.laikan.reader.core.utils.EncryptUtils;
import com.laikan.reader.core.utils.LoadingDialog;
import com.laikan.reader.core.utils.PublicUtil;
import com.socks.library.KLog;

import java.io.File;
import java.lang.reflect.Type;
import java.util.*;

/**
 * Created by wx
 *
 * @date 2016/5/25/14:55
 * @description
 */
public class ScanViewAdapter {

    private static int PREVIOUS_CHAPTER = 0;
    private static int CURRENT_CHAPTER = 1;
    private static int NEXT_CHAPTER = 2;

    Context context;
    PageFactory pageFactory;
    PageStyleSet css;
    int chapterIdIndex = 0;
    ScanView scanView;
    private int index = 0;
    public List<ChapterBean> chapData;
    private String bookId;
    private boolean isOpen = false;
    //判断是否能滑动
    private boolean isdraw = true;
    private final static String SKEY = "123456789012345678901234567890123456789088888888";
    private OnBuyListener onBuyListener;
    LoadingDialog mLoadingDialog;
    private boolean isShowProgress = false;

    private InteractiveEvent interAcEvent;

    public Map<Integer, ChapterStatus> map;

    public void initChapterCache() {
        map = new HashMap<>();
    }

    public void clearCache(int chapterIdIndex) {
        if (map != null) {
            if (chapterIdIndex > 2) {
                if (map.get(chapterIdIndex - 2) != null) {
                    map.remove(chapterIdIndex - 2);
                }
            }
            if (map.get(chapterIdIndex + 2) != null) {
                map.remove(chapterIdIndex + 2);
            }
        }
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    scanView.removeAllViews();
                    scanView.setAdapter(ScanViewAdapter.this, PageStyleSet.screenWidth, PageStyleSet.screenHeight);
                    break;
                case 2:
                    ToastMgr.showShortToast("已经是最后一章了");
                    break;
                case 3:
                    ToastMgr.showShortToast("章节正在加载中...");
                    break;
                case 4:
                    ToastMgr.showShortToast("已经是第一章了");
                    break;
                case 5:
                    ToastMgr.showShortToast("已经是最后一页了");
                    break;
                case 6:
                    ToastMgr.showShortToast("加载数据失败。。。");
                    break;
                case 7:
                    ToastMgr.showShortToast("已经是第一页了");
                    break;
                case 8:
                    if (isShowProgress) {
                        mLoadingDialog.show();
                    }
                    break;
                case 9:
                    ToastMgr.showShortToast("服务器连接失败");
                    break;
            }

        }
    };

    public ScanViewAdapter(Context context, PageFactory pageFactory, PageStyleSet css, ScanView scanView, List<ChapterBean> chapData1, String bookId, String bookName, String
        group) {
//        ChapterState chapterState = new ChapterState();
//        chapterState.getSuccess(EnumModle.faile);
        chapData = new ArrayList<ChapterBean>();
        this.scanView = scanView;
        this.context = context;
        this.pageFactory = pageFactory;
        this.css = css;
        interAcEvent = new InteractiveEvent(context, bookId, bookName, group);
        this.scanView.setInEnevt(interAcEvent);
        this.bookId = bookId;
        mLoadingDialog = new LoadingDialog(context);
        chapData.clear();
        this.chapData = chapData1;
        initChapterCache();
        initCallBack();
        new Thread() {
            @Override
            public void run() {

                getRecContent(false);

            }
        }.start();

    }

    public boolean isCurrChapterLastPage() {

        if (map.get(chapterIdIndex) != null && index == map.get(chapterIdIndex).getChapterList().size() - 1) {
            return true;
        }
        return false;
    }

    /**
     * 章节更新
     *
     * @param upChapter
     */
    public void updataDirectory(List<ChapterBean> upChapter) {
        if (upChapter.size() != chapData.size()) {
            chapData.clear();
            chapData = upChapter;
            checkData(chapterIdIndex + 1, NEXT_CHAPTER);
        }

    }

    public void getRecContent(boolean boo) {
        isShowProgress = boo;
        handler.sendEmptyMessage(8);
        scanView.isMoveInit = false;
        chapterIdIndex = SPUtil.getInt(bookId + "chaptep_rec", 0);
        if (chapterIdIndex <= 0) {
            chapterIdIndex = 0;
        }
        index = SPUtil.getInt(bookId + "recCurPage", 0);
        openBook(chapterIdIndex);
    }

    /**
     * 删除章节卷
     */
    private void deleteVolume(ArrayList<ChapterBean> chapData1) {
        for (int i = 0; i < chapData1.size(); i++) {
            if (!chapData1.get(i).isVolume()) {
                chapData.add(chapData1.get(i));
            }
        }
    }

    public String getChapterName() {
        return chapData.get(chapterIdIndex).getName();
    }

    public int getChapterPageSize() {
        if (map.get(chapterIdIndex) != null) {
            if (map.get(chapterIdIndex).isCompData()) {
                return map.get(chapterIdIndex).getChapterList().size();
            }
        }
        return 0;
    }

    /**
     * 拖动跳转页面
     *
     * @param seekIndex
     */
    public void referPage(int seekIndex) {
        this.index = seekIndex;
        handler.sendEmptyMessage(1);
    }

    /**
     * 点击下一章按钮
     */
    public void nextChapter() {

        if (chapterIdIndex + 1 > chapData.size() - 1) {
            handler.sendEmptyMessage(2);
            return;
        }
        if (map.get(chapterIdIndex + 1) == null) {
            if (!ActivityUitl.isNetworkAvailable(context)) {
                handler.sendEmptyMessage(9);
                return;
            }
        }
        if (!map.get(chapterIdIndex + 1).isFree()) {

            if (onBuyListener != null) {
                onBuyListener.setBuy(2);
                return;
            }
        }
        if (!map.get(chapterIdIndex + 1).isCompData()) {
            handler.sendEmptyMessage(3);
            return;
        }
        if (map.get(chapterIdIndex + 1) != null) {
            if (map.get(chapterIdIndex + 1).isCompData()) {
                index = map.get(chapterIdIndex).getChapterList().size() - 1;
                addIndex();
                handler.sendEmptyMessage(1);
            }
        }

    }

    /**
     * 点击上一章按钮
     */
    public void preChapter() {

        if (chapterIdIndex - 1 < 0) {
            handler.sendEmptyMessage(4);
            return;
        }
        if (map.get(chapterIdIndex + 1) == null) {
            if (!ActivityUitl.isNetworkAvailable(context)) {
                handler.sendEmptyMessage(9);
                return;
            }
        }
        if (!map.get(chapterIdIndex - 1).isFree()) {

            if (onBuyListener != null) {
                onBuyListener.setBuy(0);
                return;
            }
        }
        if (!map.get(chapterIdIndex - 1).isCompData()) {
            handler.sendEmptyMessage(3);
            return;
        }
        index = 0;
        minusIndex();
        index = 0;
        handler.sendEmptyMessage(1);
    }

    /**
     * 初始化回调
     * 数据加载完成回调
     */
    private void initCallBack() {

        css.setRePageInter(new PageStyleSet.RePageInter() {
            @Override
            public void repage() {
                handler.sendEmptyMessage(1);
            }
        });
        /**
         * 书籍加载完成回调
         * status  0 是前一章    1 是当前章     2是后一章
         */
        pageFactory.setOnCompleteData(new PageFactory.OnCompleteData() {

            //重新加载数据
            @Override
            public void reloadPage(ChapterStatus chapter, int staus) {

                if (staus == 0) {
                    if (map.get(chapterIdIndex + 1) != null && !map.get(chapterIdIndex + 1).isFree()) {
                        pageFactory.setbookData(map.get(chapterIdIndex), 1, false);
                    }else {
                        if (chapterIdIndex + 1 < chapData.size()) {
                            pageFactory.setbookData(map.get(chapterIdIndex + 1), 2, true);
                        }else {
                            isOpen = false;
                            pageFactory.setbookData(map.get(chapterIdIndex), 1, false);
                        }
                    }
                    return;
                }else if (staus == 2) {
                    isOpen = false;
                    pageFactory.setbookData(map.get(chapterIdIndex), 1, false);
                    return;

                }
            }

            //加载数据
            @Override
            public void complete(ChapterStatus chapter, int staus) {

                //初始化openBook
                if (isOpen) {
                    if (staus == 0) {
                        if (chapterIdIndex + 1 < chapData.size()) {

                            checkData(chapterIdIndex + 1, NEXT_CHAPTER);
                        }else {
                            checkData(chapterIdIndex, CURRENT_CHAPTER);
                        }
                        return;
                    }else if (staus == 2) {
                        checkData(chapterIdIndex, CURRENT_CHAPTER);
                        isOpen = false;
                        return;

                    }
                }
                if (staus == 1) {
                    if (mLoadingDialog != null) {
                        mLoadingDialog.dismiss();
                    }
                    scanView.isMoveInit = true;
                    handler.sendEmptyMessage(1);

                }else {
                    if (staus == 0) {
                        if (map.get(chapterIdIndex - 1).isReferPage()) {
                            refreCompletePrePage(chapter);
                        }
                    }else if (staus == 2) {
                        if (map.get(chapterIdIndex + 1).isReferPage()) {
                            refreCompleteNextPage(chapter);
                        }

                    }
                }
            }

        });
    }

    private void refreCompleteNextPage(ChapterStatus chap) {

        map.get(chap.getChapterIndex()).setReferPage(true);
        handler.sendEmptyMessage(1);
    }

    private void refreCompletePrePage(ChapterStatus chap) {

        map.get(chapterIdIndex - 1).setReferPage(false);
        handler.sendEmptyMessage(1);
    }

    /**
     * 打开书籍
     * 根据章节id的下标来打打开书籍
     *
     * @param chapterIdIndex
     */

    public void openBook(int chapterIdIndex) {
        this.chapterIdIndex = chapterIdIndex;
        isOpen = true;
        if (chapterIdIndex == 0) {
            if(chapData.size()==1){
                checkData(chapterIdIndex, CURRENT_CHAPTER);
            }else{
                checkData(chapterIdIndex + 1, NEXT_CHAPTER);
            }
        }else {
            checkData(chapterIdIndex - 1, PREVIOUS_CHAPTER);
        }
    }

    private String chapterDecodeContent;

    /**
     * 0 表示前章  1  表示当前章    2表示下一张
     *
     * @param cIndex
     * @param status
     */
    private void checkData(final int cIndex, final int status) {
        clearCache(chapterIdIndex);
        final boolean changeStatus = cIndex >chapData.size() - 1 || cIndex < 0;

        if (!changeStatus) {
            if (map.get(cIndex) == null) {
                map.put(cIndex, new ChapterStatus());
            }
            map.get(cIndex).setChapterIndex(cIndex);
            new Thread() {
                @Override
                public void run() {
                    File file = PublicUtil.getRootPath();
                    file = new File(file.getPath() + "/LaikanReader/book/" + bookId + "/" + chapData.get(cIndex).getId());
                    if (file.exists()) { // 从本地读取数据
                        chapterDecodeContent = EncryptUtils.decrypt(file, SKEY);
                        if ("".equals(chapterDecodeContent)) {
                            getData(cIndex, changeStatus ? CURRENT_CHAPTER : status);
                        }else {
                            ParseJosn(cIndex, chapterDecodeContent, false, changeStatus ? CURRENT_CHAPTER : status);
                        }
                    }else { // 从网络异步读取数据
                        getData(cIndex, changeStatus ? CURRENT_CHAPTER : status);
                    }
                }
            }.start();
        }
    }

    /**
     * 初始化三个view
     *
     * @param vid
     *
     * @return
     */
    public PageView getView(int vid, int page) {
        PageView pageView;
        if (map.get(chapterIdIndex) != null && map.get(chapterIdIndex).isCompData()) {
            if (vid >= map.get(chapterIdIndex).getChapterList().size() - 1) {
                if (page == 0) {
                    vid = map.get(chapterIdIndex).getChapterList().size() - 2;
                }else if (page == 1) {
                    vid = map.get(chapterIdIndex).getChapterList().size() - 1;
                    index = map.get(chapterIdIndex).getChapterList().size() - 1;
                }
            }
        }

        if (chapterIdIndex != 0 && vid == -1) {
            if (map.get(chapterIdIndex - 1) != null && map.get(chapterIdIndex - 1).isCompData()) {
                if (map.get(chapterIdIndex - 1).isFree()) {
                    pageView = new PageView(context, map.get(chapterIdIndex - 1), pageFactory, map.get(chapterIdIndex - 1).getChapterList().size() - 1, css);
                    return pageView;
                }
            }
        }
        if (map.get(chapterIdIndex) != null) {
            if (map.get(chapterIdIndex).isCompData()) {
                if (vid > map.get(chapterIdIndex).getChapterList().size() - 1) {

                    if (chapterIdIndex + 1 >= chapData.size()) {
                        pageView = new PageView(context, map.get(chapterIdIndex), pageFactory, -1, css);
                        return pageView;
                    }
                    if (map.get(chapterIdIndex + 1) != null && map.get(chapterIdIndex + 1).isCompData()) {
                        if (map.get(chapterIdIndex + 1).isFree()) {
                            pageView = new PageView(context, map.get(chapterIdIndex + 1), pageFactory, 0, css);
                            return pageView;
                        }
                    }

                }
            }
        }

        pageView = new PageView(context, map.get(chapterIdIndex), pageFactory, vid, css);
        return pageView;
    }

    /**
     * 刷新界面 点击翻页
     *
     * @param view
     * @param up_down 是0的话往前翻页，非0的话往后翻页
     */
    public void refreshPage(PageView view, int up_down) {

        if (up_down == 0) {

            if (index == 0) {
                if (chapterIdIndex - 1 < 0) {
                    return;
                }
                ChapterStatus preChapter = map.get(chapterIdIndex - 1);
                if (preChapter != null) {
                    if (preChapter.isCompData()) {
                        view.setPages(preChapter);
                        view.afresh(preChapter.getChapterList().size() - 1);
                    }else {
                        preChapter.setReferPage(true);
                    }
                }
            }else {
                view.setPages(map.get(chapterIdIndex));
                view.afresh(index - 1);
            }

        }else if (up_down == 1) {

            if (isdraw) {
                if (map.get(chapterIdIndex) != null) {

                    if (map.get(chapterIdIndex) != null && map.get(chapterIdIndex).isCompData()) {
                        if (index == map.get(chapterIdIndex).getChapterList().size() - 1) {
                            if (chapterIdIndex + 1 > chapData.size() - 1) {
                                return;
                            }
                            if (map.get(chapterIdIndex + 1) != null) {

                                if (map.get(chapterIdIndex + 1).isCompData()) {
                                    view.setPages(map.get(chapterIdIndex + 1));
                                    view.afresh(0);
                                }else {
                                    map.get(chapterIdIndex + 1).setReferPage(true);
                                    //                                view.loadData();
                                }
                            }
                        }else {
                            view.setPages(map.get(chapterIdIndex));
                            view.afresh(index + 1);
                        }
                    }else {
                        if (map.get(chapterIdIndex + 1) != null) {
                            view.setPages(map.get(chapterIdIndex + 1));
                            view.afresh(0);
                        }
                    }

                }
            }
        }
    }

    /**
     * 增加index 控制往下翻页翻章
     */
    public void addIndex() {

        index++;
        if (isdraw) {
            if (index > map.get(chapterIdIndex).getChapterList().size() - 1) {
                chapterIdIndex++;
                if (chapterIdIndex + 1 <= chapData.size()) {
                    if ((!map.get(chapterIdIndex).isCompData()) || (!map.get(chapterIdIndex).isFree())) {
                        isdraw = false;
                    }
                    scanView.prePage.setPages(map.get(chapterIdIndex));
                    scanView.currPage.setPages(map.get(chapterIdIndex));
                    scanView.nextPage.setPages(map.get(chapterIdIndex));
                    if (chapterIdIndex + 1 < chapData.size()) {
                        if (map.get(chapterIdIndex + 1) == null) {
                            map.put(chapterIdIndex + 1, new ChapterStatus());
                            checkData(chapterIdIndex + 1, NEXT_CHAPTER);
                        }else {
                            if (map.get(chapterIdIndex + 1).isReload()) {
                                pageFactory.setbookData(map.get(chapterIdIndex + 1), 2, false);
                            }
                        }

                    }
                }
                index = 0;
            }
        }

    }

    /**
     * 往前翻页
     */

    public void minusIndex() {
        index--;

        if (index < 0) {
            chapterIdIndex--;
            scanView.prePage.setPages(map.get(chapterIdIndex));
            scanView.currPage.setPages(map.get(chapterIdIndex));
            scanView.nextPage.setPages(map.get(chapterIdIndex));

            //            if(map.get(chapterIdIndex).isReferPage()){
            //                handler.sendEmptyMessage(1);
            //            }
            if (chapterIdIndex > 0) {
                if (map.get(chapterIdIndex - 1) == null) {
                    map.put(chapterIdIndex - 1, new ChapterStatus());
                    //                    checkData(chapterIdIndex - 1, 0);
                    preLoadPre(chapterIdIndex - 1, 0);
                }else {
                    if (map.get(chapterIdIndex - 1).isReload()) {
                        pageFactory.setbookData(map.get(chapterIdIndex - 1), 0, false);
                    }
                }
            }
            index = map.get(chapterIdIndex).getChapterList().size() - 1;
        }
    }

    /**
     * 章节下标
     *
     * @return
     */
    public int getChapterIdIndex() {
        return chapterIdIndex;
    }

    /**
     * 购买完成之后下一张重新加载
     */
    public void setNexReloadNotFree() {
        checkData(chapterIdIndex + 1, NEXT_CHAPTER);
    }

    /**
     * 购买完成之后上一张重新加载
     */
    public void setPreReloadNotFree() {
        checkData(chapterIdIndex - 1, NEXT_CHAPTER);
    }

    /**
     * 购买完成之后当前章重新加载
     */
    public void setCurrReloadNotFree() {

        checkData(chapterIdIndex, CURRENT_CHAPTER);
    }

    /**
     * 获取下标
     *
     * @return
     */
    public int getIndex() {
        return index;
    }

    /**
     * 获取第一个收费章节的名称
     *
     * @return
     */
    public String getChargeNextChapterId() {
        if (chapterIdIndex + 1 < chapData.size()) {
            return chapData.get(chapterIdIndex + 1).getId();
        }
        return "";
    }

    /**
     * 获取第一个收费章节的名称
     *
     * @return
     */
    public String getChargePreChapterId() {

        if (chapterIdIndex - 1 > 0) {
            return chapData.get(chapterIdIndex - 1).getId();
        }
        return "";
    }

    /**
     * 获取第一个收费章节的名称
     *
     * @return
     */
    public String getChargeCurrChapterId() {
        if (chapterIdIndex + 1 < chapData.size()) {
            return chapData.get(chapterIdIndex).getId();
        }
        return "";
    }

    /**
     * 提前判断往下翻页
     *
     * @return
     */
    public boolean isNextPage(int type) {
        if (chapterIdIndex >= chapData.size() - 1) {
            if (map.get(chapterIdIndex) != null && index == map.get(chapterIdIndex).getChapterList().size() - 1) {
                handler.sendEmptyMessage(5);
                return false;
            }

        }
        if (index == map.get(chapterIdIndex).getChapterList().size() - 1) {
            if (map.get(chapterIdIndex + 1) != null) {
                if (!map.get(chapterIdIndex + 1).isFree()) {
                    if (onBuyListener != null && type == 0) {
                        onBuyListener.setBuy(2);
                    }
                    return false;
                }
                if (!map.get(chapterIdIndex + 1).isCompData()) {
                    if (!ActivityUitl.isNetworkAvailable(context)) {
                        handler.sendEmptyMessage(9);
                    }else {
                        handler.sendEmptyMessage(3);
                        //连接网络预加载下一章
                        if (chapterIdIndex + 1 < chapData.size()) {
                            preLoadNext(chapterIdIndex + 1, 2);
                        }

                    }
                    return false;
                }
            }else {
                if (!ActivityUitl.isNetworkAvailable(context)) {
                    handler.sendEmptyMessage(9);
                }
                return false;
            }
        }

        return isdraw;

    }

    /**
     * 判断往回翻页
     *
     * @return
     */
    public boolean isPrePage() {

        if (chapterIdIndex <= 0) {
            if (index <= 0) {
                handler.sendEmptyMessage(7);
                return false;
            }
        }
        if (index == 0 && !map.get(chapterIdIndex - 1).isFree()) {

            if (onBuyListener != null) {
                onBuyListener.setBuy(0);

            }
            return false;
        }
        if (index == 0 && map.get(chapterIdIndex - 1) == null) {
            if (!ActivityUitl.isNetworkAvailable(context)) {
                handler.sendEmptyMessage(9);
            }
            return false;
        }
        if (index == 0 && !map.get(chapterIdIndex - 1).isCompData()) {

            if (!ActivityUitl.isNetworkAvailable(context)) {
                handler.sendEmptyMessage(9);
            }else {
                handler.sendEmptyMessage(3);
                if (chapterIdIndex - 1 >= 0) {
                   checkData(chapterIdIndex - 1, PREVIOUS_CHAPTER);
                }
            }
            return false;
        }
        return true;
    }

    /**
     * 预加载下一章
     *
     * @param cIndex
     * @param status
     */
    private void preLoadNext(final int cIndex, final int status) {
        if (cIndex > chapData.size() - 1) {
            checkData(chapterIdIndex, CURRENT_CHAPTER);
            return;
        }
        if (cIndex < 0) {
            checkData(chapterIdIndex, CURRENT_CHAPTER);
            return;
        }
        if (map.get(cIndex) == null) {
            map.put(cIndex, new ChapterStatus());
        }
        map.get(cIndex).setChapterIndex(cIndex);

        RequestListener requestListener = new RequestListener() {
            @Override
            public void onPreExecute() {
            }

            @Override
            public void onSuccess(HttpResponse httpResponse) {
                try {
                    ParseJosn(cIndex, httpResponse.responseContent, true, status);
                    if (map.get(chapterIdIndex + 1) != null) {
                        pageFactory.setbookData(map.get(chapterIdIndex + 1), 2, true); // 请求完 下张重新进行分页排版
                    }
                }catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(VolleyErrorHandler errorHandler) {
                if (status == 2 || status == 0) {
                    checkData(chapterIdIndex, CURRENT_CHAPTER);
                }
            }

            @Override
            public void onFinish() {
            }
        };
        if (map.get(cIndex) != null) {
            map.get(cIndex).setLoad(true);
            map.get(cIndex).setChapterId(chapData.get(cIndex).getId());
        }
        HashMap<String, String> map = new HashMap<>();
        map.put("sd", SPUtil.getString("token", ""));

        Requester requester = new Requester();
        requester.setUrl(APIProtocol.getRootURL() + "book/" + bookId + "_" + chapData.get(cIndex).getId());
        requester.setMapBody(map);
        HttpApiRequestEngine.getInstance().httpPostRequest(requester, requestListener);

//        HttpApiRequestEngine.getInstance().httpPostRequest(APIProtocol.getRootURL() + "book/" + bookId + "_" + chapData.get(cIndex).getId(), map, null, null, requestListener);
    }

    /**
     * 预加载上一章
     *
     * @param cIndex
     * @param status
     */
    private void preLoadPre(final int cIndex, final int status) {
        clearCache(chapterIdIndex);

        if (cIndex > chapData.size() - 1) {
            checkData(chapterIdIndex, CURRENT_CHAPTER);
            return;
        }
        if (cIndex < 0) {
            checkData(chapterIdIndex, CURRENT_CHAPTER);
            return;
        }
        if (map.get(cIndex) == null) {
            map.put(cIndex, new ChapterStatus());
        }
        map.get(cIndex).setChapterIndex(cIndex);
        File file = PublicUtil.getRootPath();
        file = new File(file.getPath() + "/LaikanReader/book/" + bookId + "/" + chapData.get(cIndex).getId());
        if (file.exists()) {   //本地
            final File finalFile = file;
            new Thread() {
                @Override
                public void run() {
                    chapterDecodeContent = EncryptUtils.decrypt(finalFile, SKEY);
                    if ("".equals(chapterDecodeContent)) {
                        getData(cIndex, status);
                    }else {
                        ParseJosn(cIndex, chapterDecodeContent, false, status);
                        if (map.get(chapterIdIndex - 1) != null) {
                            pageFactory.setbookData(map.get(chapterIdIndex - 1), 0, true); //本地 重新排版上一章
                        }
                    }
                }
            }.start();
        }else { // 从网络异步读取数据
            RequestListener requestListener = new RequestListener() {
                @Override
                public void onPreExecute() {}

                @Override
                public void onSuccess(HttpResponse httpResponse) {
                    try {
                        ParseJosn(cIndex, httpResponse.responseContent, true, status);
                        if (map.get(chapterIdIndex - 1) != null) {
                            pageFactory.setbookData(map.get(chapterIdIndex - 1), 0, true);  //上一章重新进行分页排版
                        }
                    }catch (Exception e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void onError(VolleyErrorHandler errorHandler) {
                    if (status == 2 || status == 0) {
                        checkData(chapterIdIndex, CURRENT_CHAPTER);
                    }
                }

                @Override
                public void onFinish() {
                }
            };
            if (map.get(cIndex) != null) {
                map.get(cIndex).setLoad(true);
                map.get(cIndex).setChapterId(chapData.get(cIndex).getId());
            }
            HashMap<String, String> map = new HashMap<>();
            map.put("sd", SPUtil.getString("token", ""));

            Requester requester = new Requester();
            requester.setUrl(APIProtocol.getRootURL() + "book/" + bookId + "_" + chapData.get(cIndex).getId());
            requester.setMapBody(map);
            HttpApiRequestEngine.getInstance().httpPostRequest(requester, requestListener);

//            HttpApiRequestEngine.getInstance().httpPostRequest(APIProtocol.getRootURL() + "book/" + bookId + "_" + chapData.get(cIndex).getId(), map, null, null,
//                requestListener);
        }
    }

    public void setNightModle(int modle) {
        css.setPaintColor(modle, true);
    }

    public void setFontType() {
        PageStyleSet.Instance().setFontType();
        reLoadData();
        entries();
    }

    /**
     * 设置背景
     *
     * @param modle
     */
    public void setBg(int modle) {
        css.setPaintColor(modle, true);

    }

    /**
     * 设置字体大小
     *
     * @param textSize
     */
    public void setFontSize(int textSize) {
        css.setTextSize((int)(textSize * PageStyleSet.density));
        reLoadData();
        entries();
    }

    /**
     * 设置行距
     *
     * @param lineSpace
     */

    public void setLineSpace(float lineSpace) {
        css.setLinSpace(lineSpace);
        reLoadData();
        entries();
    }

    private void reLoadData() {
        if (chapterIdIndex == 0) {
            if (!map.get(chapterIdIndex + 1).isFree()) {
                pageFactory.setbookData(map.get(chapterIdIndex), 1, false);
            }else {
                pageFactory.setbookData(map.get(chapterIdIndex + 1), 2, true);
            }

        }else {
            if (!map.get(chapterIdIndex - 1).isFree()) {
                if (!map.get(chapterIdIndex + 1).isFree()) {
                    pageFactory.setbookData(map.get(chapterIdIndex), 1, false);
                }else {
                    pageFactory.setbookData(map.get(chapterIdIndex + 1), 2, true);
                }
            }else {
                pageFactory.setbookData(map.get(chapterIdIndex - 1), 0, true);
            }
        }
    }

    /**
     * 便利map
     * 更新map分页
     */
    private void entries() {
        Iterator entries = map.entrySet().iterator();
        while (entries.hasNext()) {
            Map.Entry entry = (Map.Entry)entries.next();
            Integer key = (Integer)entry.getKey();
            ChapterStatus value = (ChapterStatus)entry.getValue();
            value.setReload(true);
        }
    }

    public boolean getCurrChapterLastPage() {
        return map.get(chapterIdIndex).getChapterList().size() - 1 == index;
    }

    /**
     * 访问网络 获取章节数据
     *
     * @param status 1是当前章，0是前一张，2是后一章
     * @param
     */
    private void getData(final int dataIndex, final int status) {

        RequestListener requestListener = new RequestListener() {
            @Override
            public void onPreExecute() {
                KLog.e("---------volley onPreExecute!!!");
            }

            @Override
            public void onSuccess(HttpResponse httpResponse) {
                System.out.println(httpResponse.responseContent+"------");
                try {
                    ParseJosn(dataIndex, httpResponse.responseContent, true, status);
                    //                    if(map.get(chapterIdIndex + 1) != null){
                    //                        pageFactory.setbookData(map.get(chapterIdIndex + 1), 2, true); // 请求完 下张重新进行分页排版
                    //                    }
                    //                    if(map.get(chapterIdIndex - 1) != null){
                    //                        pageFactory.setbookData(map.get(chapterIdIndex - 1), 0, true);  //上一章重新进行分页排版
                    //                    }
                }catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(VolleyErrorHandler errorHandler) {
                if (status == 2 || status == 0) {
                    checkData(chapterIdIndex, CURRENT_CHAPTER);
                }else if (status == 1) {
                    handler.sendEmptyMessage(6);
                    ((Activity)context).finish();
                }
            }

            @Override
            public void onFinish() {

            }
        };

        if (map.get(dataIndex) != null) {

            map.get(dataIndex).setLoad(true);
            map.get(dataIndex).setChapterId(chapData.get(dataIndex).getId());
        }
        HashMap<String, String> map = new HashMap<>();
        map.put("sd", SPUtil.getString("token", ""));
        System.out.println(APIProtocol.getRootURL() + "book/" + bookId + "_" + chapData.get(dataIndex).getId()+"-----");
        Requester requester = new Requester();
        requester.setUrl(APIProtocol.getRootURL() + "book/" + bookId + "_" + chapData.get(dataIndex).getId());
        requester.setMapBody(map);
        HttpApiRequestEngine.getInstance().httpPostRequest(requester, requestListener);
    }

    private void ParseJosn(final int dataIndexChapIndex, final String json, boolean isSave, final int status) {
        if (map.get(dataIndexChapIndex) == null) {
            map.put(dataIndexChapIndex, new ChapterStatus());
        }
        map.get(dataIndexChapIndex).setLoad(true);
        map.get(dataIndexChapIndex).setChapterId(chapData.get(dataIndexChapIndex).getId());
        map.get(dataIndexChapIndex).setChapterIndex(dataIndexChapIndex);
        BaseDataBean<ChapterDetailBean> result;
        Gson gson = new Gson();
        Type type = new TypeToken<BaseDataBean<ChapterDetailBean>>() {
        }.getType();
        try {
            result = gson.fromJson(json, type);

            /**
             * 限免作品章节:600 需要购买:601 余额不足:602 购买失败:603 阅读券余额不足:604
             */
            if (result != null) {
                if (null == result.getData() || !Constants.RESULT_OK.equals(result.getResult())) {
                    if ("601".equals(result.getError_no())) {

                        map.get(dataIndexChapIndex).setFree(false);
                        if (status == 1) {

                            if (onBuyListener != null) {
                                onBuyListener.setBuy(1);
                                ((ReaderDetailActivity)context).isRefreshBookChapter = true;
                            }
                        }
                        if (result.getData().isAutoBuy()) {
                            int i = -1;
                            if (status == 0) {
                                i = 0;
                            }else if (status == 2) {
                                i = 2;
                            }
                            EngineOP engineOP = new EngineOP(new EngineOP.BuyChapterListener() {
                                @Override
                                public void buySuceeess(String chid) {
                                    for (int i = 0; i < chapData.size(); i++) {
                                        if (chid.equals(chapData.get(i).getId())) {
                                            checkData(i, status);
                                        }
                                    }
                                }
                            });
                            engineOP.chapterBuy(context, bookId, chapData.get(dataIndexChapIndex).getId(), i, 3, true, true);
                        }else {
                            if (isOpen) {
                                if (status == 0) {
                                    checkData(chapterIdIndex + 1, NEXT_CHAPTER);
                                }else if (status == 2) {
                                    checkData(chapterIdIndex, CURRENT_CHAPTER);
                                    isOpen = false;
                                }
                            }
                            if (status == 1) {

                                if (onBuyListener != null) {
                                    onBuyListener.setBuy(1);

                                }

                            }
                        }
                    }else if ("602".equals(result.getError_no())) {
                        map.get(dataIndexChapIndex).setFree(false);
                        if (isOpen) {
                            if (status == 0) {
                                checkData(chapterIdIndex + 1, NEXT_CHAPTER);
                            }else if (status == 2) {
                                checkData(chapterIdIndex, CURRENT_CHAPTER);
                                isOpen = false;
                            }
                        }
                        if (status == 1) {

                            if (onBuyListener != null) {
                                onBuyListener.setBuy(1);
                                ((ReaderDetailActivity)context).isRefreshBookChapter = true;
                            }

                        }
                    }
                }else {
                    // 获取到章节内容
                    map.get(dataIndexChapIndex).setFree(true);
                    String chapterName = result.getData().getName();
                    String content = result.getData().getContent();
                    String authorSay = result.getData().getAuthorSay();
                    String chapterCmd = CmdBuild.createNormalCmd(chapterName, content, result.getData().getAuthorSay());
                    map.get(dataIndexChapIndex).setChapterName(chapterName);
                    map.get(dataIndexChapIndex).setChapterString(json);
                    map.get(dataIndexChapIndex).setChapterCmd(chapterCmd);
                    pageFactory.setbookData(map.get(dataIndexChapIndex), status, false);
                    if (isSave && !"600".equals(result.getError_no())) {
                        new Thread() {
                            @Override
                            public void run() {
                                super.run();
                                saveChapterFile(chapData.get(dataIndexChapIndex).getId(), json);
                            }
                        }.start();
                    }
                    return;
                }
            }else {
                handler.sendEmptyMessage(6);
            }

        }catch (JsonSyntaxException e) {
            e.printStackTrace();
        }

    }

    /**
     * 保存章节
     *
     * @param chapterid
     * @param json
     */
    private void saveChapterFile(final String chapterid, String json) {
        File file = PublicUtil.getRootPath();
        file = new File(file.getPath() + "/LaikanReader/book/" + bookId + "/" + chapterid);
        if (!file.isDirectory()) {
            file.delete();
            file.mkdirs();
        }
        if (!file.exists()) {
            file.mkdirs();
        }
        EncryptUtils.encrypt(new File(file.getPath()), SKEY, json);
    }

    /**
     * 购买章节回调
     */

    public interface OnBuyListener {

        public void setBuy(int type);
    }

    public void setOnBuyListener(OnBuyListener listener) {
        this.onBuyListener = listener;
    }

}